<!--
  * BOM详细物料信息
  *
  * @Author:    lmabbe
  * @Date:      2025-06-27 19:03:45
  * @Copyright  lmabbe
-->
<template>
  <div class="smart-query-form">
    <!---------- 查询表单form begin ----------->
    <a-form size="small" style="margin-bottom: 10px">
      <a-row class="smart-query-form-row">
        <a-form-item class="smart-query-form-item" label="物料类型">
          <a-select v-model:value="queryForm.materialType" :allowClear="true" :style="`width: 200px`" placeholder="物料类型">
            <a-select-option v-for="item in PRODUCT_BOM_DETAIL_MATERIAL_TYPE_ENUM" :key="item.value" :label="item.value">
              {{ item.desc }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item class="smart-query-form-item" label="物料信息">
          <a-input v-model:value="queryForm.mateialKeywords" placeholder="可查询物料编号/名称/描述/规格" style="width: 200px" />
        </a-form-item>
        <a-form-item class="smart-query-form-item" label="位置信息">
          <a-input v-model:value="queryForm.location" placeholder="可查询B面/T面" style="width: 200px" />
        </a-form-item>
        <a-form-item class="smart-query-form-item">
          <a-button type="primary" @click="onSearch">
            <template #icon>
              <SearchOutlined />
            </template>
            查询
          </a-button>
          <a-button class="smart-margin-left10" @click="resetQuery">
            <template #icon>
              <ReloadOutlined />
            </template>
            重置
          </a-button>
        </a-form-item>
      </a-row>
    </a-form>
    <!---------- 查询表单form end ----------->

    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button :disabled="bomInfoRef.postedFlag" size="small" type="primary" @click="showForm">
          <template #icon>
            <PlusOutlined />
          </template>
          新建
        </a-button>

        <a-upload
          :beforeUpload="confirmImportBom"
          :disabled="bomInfoRef.postedFlag"
          :max-count="1"
          :show-upload-list="false"
          accept=".xls,.xlsx"
          size="small"
        >
          <a-button :disabled="bomInfoRef.postedFlag" size="small">
            <CloudUploadOutlined />
            导入BOM
          </a-button>
        </a-upload>
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->

    <!---------- 表格 begin ----------->
    <a-table
      :columns="columns"
      :dataSource="tableData"
      :loading="tableLoading"
      :pagination="false"
      :scroll="{ y: 360 }"
      bordered
      rowKey="detailId"
      size="small"
    >
      <template #bodyCell="{ text, record, column }">
        <template v-if="column.dataIndex === 'materialType'">
          <span>{{ $smartEnumPlugin.getDescByValue('PRODUCT_BOM_DETAIL_MATERIAL_TYPE_ENUM', text) }}</span>
        </template>

        <template v-if="column.dataIndex === 'action'">
          <div class="smart-table-operate">
            <a-button :disabled="bomInfoRef.postedFlag" type="link" @click="showForm(record)">编辑</a-button>
            <a-button :disabled="bomInfoRef.postedFlag" danger type="link" @click="onDelete(record)">删除</a-button>
          </div>
        </template>
      </template>
    </a-table>
    <!---------- 表格 end ----------->

    <div class="smart-query-table-page">
      <a-pagination
        v-model:current="queryForm.pageNum"
        v-model:pageSize="queryForm.pageSize"
        :defaultPageSize="queryForm.pageSize"
        :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :show-total="(total) => `共${total}条`"
        :total="total"
        show-less-items
        showQuickJumper
        showSizeChanger
        @change="queryData"
        @showSizeChange="queryData"
      />
    </div>
  </div>
  <BomDetailForm ref="formRef" @reloadList="queryData" />
</template>
<script setup>
  import { reactive, ref } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
  import { bomDetailApi } from '/@/api/business/product/bom/bom-detail-api.js';
  import { smartSentry } from '/@/lib/smart-sentry';
  import BomDetailForm from './bom-detail-form.vue';
  import { PRODUCT_BOM_DETAIL_MATERIAL_TYPE_ENUM } from '/@/constants/business/product/bom/bom-detail-const.js';

  // ---------------------------- 表格列 ----------------------------

  const columns = ref([
    {
      title: 'BOM详情ID',
      dataIndex: 'detailId',
      ellipsis: true,
      width: 0,
    },
    {
      title: 'BOM编号',
      dataIndex: 'bomId',
      ellipsis: true,
      width: 0,
    },
    {
      title: '物料类型',
      dataIndex: 'materialType',
      ellipsis: true,
      width: '80px',
      align: 'center',
    },
    {
      title: '主料编码',
      dataIndex: 'mainMaterialCode',
      ellipsis: true,
      width: '100px',
      align: 'center',
    },
    {
      title: '物料编码',
      dataIndex: 'materialCode',
      ellipsis: true,
      width: '100px',
      align: 'center',
    },
    {
      title: '物料名称',
      dataIndex: 'materialName',
      ellipsis: true,
      width: '150px',
      align: 'center',
    },
    {
      title: '物料规格',
      dataIndex: 'materialSpec',
      ellipsis: true,
      width: '150px',
      align: 'center',
    },
    {
      title: '物料描述',
      dataIndex: 'materialDesc',
      ellipsis: true,
      width: '200px',
      align: 'center',
    },
    {
      title: '物料单位',
      dataIndex: 'materialUnit',
      ellipsis: true,
      width: '80px',
      align: 'center',
    },
    {
      title: '用量',
      dataIndex: 'dosage',
      ellipsis: true,
      width: '80px',
      align: 'center',
    },
    {
      title: 'T面位置',
      dataIndex: 'locationT',
      ellipsis: true,
      width: '200px',
      align: 'center',
    },
    {
      title: 'B面位置',
      dataIndex: 'locationB',
      ellipsis: true,
      width: '200px',
      align: 'center',
    },
    {
      title: '备注',
      dataIndex: 'remark',
      ellipsis: true,
      width: '200px',
      align: 'center',
    },
    {
      title: '禁用状态',
      dataIndex: 'disabledFlag',
      ellipsis: true,
      width: '80px',
      align: 'center',
    },
    {
      title: '创建人',
      dataIndex: 'createUserName',
      ellipsis: true,
      width: '80px',
      align: 'center',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      ellipsis: true,
      width: '150px',
      align: 'center',
    },
    {
      title: '更新人',
      dataIndex: 'updateUserName',
      ellipsis: true,
      width: '80px',
      align: 'center',
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      ellipsis: true,
      width: '150px',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      width: 100,
      align: 'center',
    },
  ]);

  // ---------------------------- 查询数据表单和方法 ----------------------------

  const queryFormState = {
    materialType: undefined, //物料类型:[1:主料，2:替代料]
    mateialKeywords: undefined, //物料信息查询
    location: undefined, //位置信息查询
    bomId: undefined,
    pageNum: 1,
    pageSize: 10,
  };
  // 查询表单form
  const queryForm = reactive({ ...queryFormState });
  // 表格加载loading
  const tableLoading = ref(false);
  // 表格数据
  const tableData = ref([]);
  // 总数
  const total = ref(0);

  // 重置查询条件
  function resetQuery() {
    let pageSize = queryForm.pageSize;
    Object.assign(queryForm, queryFormState);
    queryForm.pageSize = pageSize;
    queryData();
  }

  // 搜索
  function onSearch() {
    queryForm.pageNum = 1;
    queryData();
  }

  // 查询数据
  async function queryData() {
    tableLoading.value = true;
    try {
      let queryResult = await bomDetailApi.queryPage(queryForm);
      tableData.value = queryResult.data.list;
      total.value = queryResult.data.total;
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      tableLoading.value = false;
    }
  }

  //onMounted(queryData);

  // ---------------------------- 添加/修改 ----------------------------
  const formRef = ref();

  function showForm(data) {
    data['bomId'] = queryForm.bomId;
    formRef.value.show(data);
  }

  // ---------------------------- 单个删除 ----------------------------
  //确认删除
  function onDelete(data) {
    Modal.confirm({
      title: '提示',
      content: '确定要删除选吗?',
      okText: '删除',
      okType: 'danger',
      onOk() {
        requestDelete(data);
      },
      cancelText: '取消',
      onCancel() {},
    });
  }

  //请求删除
  async function requestDelete(data) {
    SmartLoading.show();
    try {
      let deleteForm = {
        goodsIdList: selectedRowKeyList.value,
      };
      await bomDetailApi.delete(data.detailId);
      message.success('删除成功');
      queryData();
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  }

  // ---------------------------- 批量删除 ----------------------------

  // 选择表格行
  const selectedRowKeyList = ref([]);

  const bomInfoRef = reactive({
    bomVer: '',
    materialCode: '',
    customerCode: '',
    postedFlag: false,
  });

  function setBomInfo(bomInfo) {
    queryForm.bomId = bomInfo.bomId;
    bomInfoRef.bomVer = bomInfo.bomVer;
    bomInfoRef.materialCode = bomInfo.materialCode;
    bomInfoRef.customerCode = bomInfo.belongCustomerCode;
    bomInfoRef.postedFlag = bomInfo.postedFlag;
    queryData();
  }

  function confirmImportBom(file) {
    Modal.confirm({
      title: '提示',
      content: '确定要导入数据吗?导入会删除旧的数据！',
      okText: '导入',
      okType: 'danger',
      onOk() {
        importBom(file);
      },
      cancelText: '取消',
      onCancel() {},
    });
  }

  async function importBom(file) {
    // 检查文件类型
    const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.type === 'application/vnd.ms-excel';

    if (!isExcel) {
      message.error('只能上传Excel文件!');
      return false;
    }

    SmartLoading.show();
    try {
      await bomDetailApi.importBom(file, bomInfoRef).then((res) => {
        console.log(res);
        message.success('导入成功');
        onSearch();
        SmartLoading.hide();
      });
    } finally {
      SmartLoading.hide();
    }
    // 返回false阻止默认上传行为
    return false;
  }

  defineExpose({
    setBomInfo,
  });
</script>
